  //
//  MusicPlayViewController.m
//  CatMusic
//
//  Created by dllo on 15/4/23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "MusicPlayViewController.h"
#import "UIImageView+WebCache.h"
#import <AVFoundation/AVFoundation.h>
#import "PlayerSingleton.h"
#import "BaseModel.h"
#import "DataBaseHandle.h"
#import <MediaPlayer/MediaPlayer.h>
#import "AFNetworkReachabilityManager.h"
#import "MBProgressHUD.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface MusicPlayViewController ()<AVAudioPlayerDelegate, UIAlertViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, copy)NSString *path;
@property(nonatomic, retain)UISlider *musicSlider;                  // 音乐进度条
@property(nonatomic, retain)UILabel *endSliderLabel;                // 音乐总时长
@property(nonatomic, retain)UILabel *beginSliderLabel;              // 音乐进度条开始的label
@property(nonatomic, retain)UIProgressView *musicProgress;          //音乐缓冲条
@property(nonatomic, copy)NSString *totalTime;                      // 监听事件中的,总时间
@property(nonatomic, assign)CGFloat endTime;                        // 当前歌曲总时长
@property(nonatomic ,retain) id playbackTimeObserver;               // 监听事件用到的
@property(nonatomic, retain)UIButton *backButton;                   // 返回按钮
@property(nonatomic, retain)UIButton *playListButton;               // 播放列表按钮
@property(nonatomic, retain)UIImageView *backgroundImageView;       // 背景图片view
@property(nonatomic, retain)UILabel *titleLabel;                    // 标题
@property(nonatomic, retain)UIView *playView;                       // 最下面的播放栏
@property(nonatomic, retain)UIButton *playButton;                   // 播放按钮
@property(nonatomic, retain)UIButton *lastMusicButton;              // 上一首按钮
@property(nonatomic, retain)UIButton *nextMusicButton;              // 下一首按钮
@property(nonatomic, retain)UIView *musicListQueue;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)UIImageView *bacgroundView;
@property(nonatomic, retain)MBProgressHUD *mbProView;
@property(nonatomic, retain)UISwipeGestureRecognizer *rightSwipe;

@end

@implementation MusicPlayViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.modelArr = [NSMutableArray array];
//        [PlayerSingleton sharePlayerSingleton].tryListenArr = [NSMutableArray array];
    }
    return  self;
}


- (void)dealloc {
    [_musicSlider release];
    [_endSliderLabel release];
    [_beginSliderLabel release];
    [_musicProgress release];
    [_backgroundImageView release];
    [_titleLabel release];
    [_playView release];
    [_musicListQueue release];
    [_tableView release];
    [_bacgroundView release];
    [[PlayerSingleton sharePlayerSingleton].playerItem removeObserver:self forKeyPath:@"status" context:nil];
    [[PlayerSingleton sharePlayerSingleton].playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:[PlayerSingleton sharePlayerSingleton].playerItem];
    [[PlayerSingleton sharePlayerSingleton].player removeTimeObserver:self.playbackTimeObserver];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
//    [self isCurrentMusic:self.indexPath];              // 加载歌曲
    [self createBackgroundImageView];   // 背景图片
    [self createTitle];                 // 设置标题
    [self createNavigationBarButton];   // 设置页头
    [self createPlayStateButton];       // 设置播放按钮
    [self createMusicSlider];           // 创建音乐条
//    [self isCurrentMusic:self.indexPath];// 加载歌曲
//     [self setLockInfo];
    
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                [self alertViewCancel];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                [self alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                [self isCurrentMusic:self.indexPath];// 加载歌曲
                    [self setLockInfo];
                break;
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];
    self.rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipe:)];
    self.rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:self.rightSwipe];
    [self.rightSwipe release];

}

- (void)rightSwipe:(UISwipeGestureRecognizer *)right
{
    [self.navigationController popViewControllerAnimated:YES];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}


- (void)alertViewCancel
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络断开连接" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
    [alert show];
}

- (void)alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"手机自带网络" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
    [alert show];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}
-(void)viewDidDisappear:(BOOL)animated{
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

- (void)getMusicListToSingletonArr
{
        // 对播放列表进行归档操作
    if (self.modelArr !=nil) {
        NSMutableDictionary *musicListDic = [NSMutableDictionary dictionary];
        NSString *index = [NSString stringWithFormat:@"%ld", (long)self.indexPath];
        [musicListDic setObject:index forKey:@"indexPath"];
        [musicListDic setObject:self.modelArr forKey:@"modelArr"];
        
        NSArray *sandBoxPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
        NSString *sandPath = [sandBoxPath lastObject];
        NSString *musicListFilePath = [sandPath stringByAppendingPathComponent:@"musicList.plist"];
        
        [NSKeyedArchiver archiveRootObject:musicListDic toFile:musicListFilePath];
        NSLog(@"%@", musicListFilePath);
    }
    
}


// 返回按钮和列表按钮
- (void)createNavigationBarButton
{
    // 返回按钮
    self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.backButton.frame = CGRectMake(20, 50, 50, 50);
    self.backButton.center = CGPointMake(30, 20 + self.titleLabel.frame.size.height / 2);
    [self.backButton setBackgroundImage:[UIImage imageNamed:@"iconfont-back"] forState:UIControlStateNormal];
    [self.view addSubview:self.backButton];
    [self.backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    // 列表按钮
    self.playListButton = [[UIButton alloc] init];
    self.playListButton.frame = CGRectMake(WIDTH / 11 * 9, 50, 30, 30);
    self.playListButton.center = CGPointMake(WIDTH / 11 * 10, 20 + self.titleLabel.frame.size.height / 2);
    [self.playListButton setBackgroundImage:[UIImage imageNamed:@"iconfont-liebiao"] forState:UIControlStateNormal];
    [self.playListButton addTarget:self action:@selector(showMusicList) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.playListButton];
}

// 设置背景图片
- (void)createBackgroundImageView
{
    // 背景图片
    self.backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT)];
    self.backgroundImageView.image = [UIImage imageNamed:@"placeHolder"];
    NSString *pic = [self.modelArr[self.indexPath] pic_url];
    NSURL *pic_url = [NSURL URLWithString:pic];
    if (pic != nil) {
        
        [self.backgroundImageView sd_setImageWithURL:pic_url placeholderImage:[UIImage imageNamed:@"placeHolder"]];
    }
    else
    {
    NSMutableArray *images = [NSMutableArray array];
        for (NSInteger i = 1; i < 8; i++) {
            NSString *name = [NSString stringWithFormat:@"1-%ld.png", (long)i];
            UIImage *image = [UIImage imageNamed:name];
            [images addObject:image];
        }
        self.backgroundImageView.animationImages = images;
        self.backgroundImageView.animationDuration = 5;
        self.backgroundImageView.animationRepeatCount = 0;
        [self.backgroundImageView startAnimating];
    }
    
    [self.view addSubview:self.backgroundImageView];
    
}

// 设置标题
- (void)createTitle
{
    // title
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT / 14)];
    self.titleLabel.text = [self.modelArr[self.indexPath] song_name];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.backgroundColor = [UIColor lightGrayColor];
    self.titleLabel.alpha = 0.5;
    [self.view addSubview:self.titleLabel];
    [self.titleLabel release];
    
}

// 设置播放状态的按钮:下面的播放条,播放或暂停按钮,上一首下一首按钮
- (void)createPlayStateButton
{
    // 播放条
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT / 21 * 17, WIDTH, HEIGHT / 17 * 4)];
    self.playView.backgroundColor = [UIColor lightGrayColor];
    self.playView.alpha = 0.5;
    [self.view addSubview:self.playView];
    [self.playView release];
    
    // 播放条上的播放暂停按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.playButton.frame = CGRectMake(WIDTH / 2, 600, HEIGHT / 7, HEIGHT / 7);
    self.playButton.center = CGPointMake(WIDTH / 2,HEIGHT - self.playView.frame.size.height / 8 * 3);
    if ([[PlayerSingleton sharePlayerSingleton].playState isEqualToString:@"NO"]) {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-play"] forState:UIControlStateNormal];
    }
    else if([[PlayerSingleton sharePlayerSingleton].playState isEqualToString:@"YES"])
    {
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-pause"] forState:UIControlStateNormal];
    }
    [self.view addSubview:self.playButton];
    [self.playButton addTarget:self action:@selector(playClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 播放条上的上一首
    self.lastMusicButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.lastMusicButton.frame = CGRectMake(WIDTH / 3 * 2, HEIGHT / 11, HEIGHT / 10, HEIGHT / 10);
    self.lastMusicButton.center = CGPointMake(WIDTH / 4, HEIGHT - self.playView.frame.size.height / 8 * 3);
    [self.lastMusicButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shangyishou"] forState:UIControlStateNormal];
    [self.self.view addSubview:self.lastMusicButton];
    [self.lastMusicButton addTarget:self action:@selector(lastMusicClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 播放条上的下一首
    self.nextMusicButton =  [UIButton buttonWithType:UIButtonTypeSystem];
    self.nextMusicButton.frame = CGRectMake(WIDTH / 3 * 2, HEIGHT / 11, HEIGHT / 10, HEIGHT / 10);
    self.nextMusicButton.center = CGPointMake(WIDTH / 4 * 3 , HEIGHT - self.playView.frame.size.height / 8 * 3);
    [self.nextMusicButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xiayishou"] forState:UIControlStateNormal];
    [self.view addSubview:self.nextMusicButton];
    [self.nextMusicButton addTarget:self action:@selector(nextMusicClick) forControlEvents:UIControlEventTouchUpInside];
}


// 音乐进度条
- (void)createMusicSlider
{
    // 进度条
    
    
    self.musicSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, HEIGHT / 16 * 13 , self.view.frame.size.width, 10)];
    [self.musicSlider addTarget:self action:@selector(musicSlierChangeValue:) forControlEvents:UIControlEventValueChanged];
    [self.musicSlider addTarget:self action:@selector(musicSlierChangeValueEnd:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.musicSlider];
    [self.musicSlider release];
    self.musicSlider.minimumValue = 0;
    
    self.beginSliderLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, HEIGHT / 16 * 13 + 15, 50, 20)];
    self.beginSliderLabel.font = [UIFont systemFontOfSize:12];
    self.beginSliderLabel.text = @"00:00";
    [self.view addSubview:self.beginSliderLabel];
    [self.beginSliderLabel release];
    
    self.endSliderLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH - 40, HEIGHT / 16 * 13 + 15, 50, 20)];
    self.endSliderLabel.text = @"00:00";
    self.endSliderLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:self.endSliderLabel];
    [self.endSliderLabel release];
}




#pragma mark - 通知
/**
 *  添加播放器通知
 */
-(void)addNotification{
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:[PlayerSingleton sharePlayerSingleton].player.currentItem];
}


- (void)playbackFinished:(NSNotification *)notification
{
    if (self.indexPath < self.modelArr.count - 1) {
        [self isCurrentMusic:++self.indexPath];
        [self setLockInfo];
        NSLog(@"sss");
    }
    else
    {
        [[PlayerSingleton sharePlayerSingleton].player pause];
        NSLog(@"Play end");
    }

//    [self isCurrentMusic:++self.indexPath];
}
/**
 *  给AVPlayerItem添加监控
 *
 *  @param playerItem AVPlayerItem对象
 */
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];

}

- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    self.playbackTimeObserver = [[PlayerSingleton sharePlayerSingleton].player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;// 计算当前在第几秒
        [self updateMusicSlider:currentSecond];
         self.beginSliderLabel.text = [self convertTime:currentSecond];
        self.endSliderLabel.text = [self convertTime:self.endTime - currentSecond];
    }];
}

- (void)musicSlierChangeValue:(id)sender {
    UISlider *slider = (UISlider *)sender;
    NSLog(@"value change:%f",slider.value);
    if (slider.value == 0.000000) {
        [[PlayerSingleton sharePlayerSingleton].player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
            [[PlayerSingleton sharePlayerSingleton].player play];
        }];
    }
}

- (void)musicSlierChangeValueEnd:(id)sender {
    UISlider *slider = (UISlider *)sender;
    NSLog(@"value end:%f",slider.value);
    CMTime changedTime = CMTimeMakeWithSeconds(slider.value, 1);
    [[PlayerSingleton sharePlayerSingleton].player seekToTime:changedTime completionHandler:^(BOOL finished) {
        [[PlayerSingleton sharePlayerSingleton].player play];
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-pause"] forState:UIControlStateNormal];
    }];
}



- (void)updateMusicSlider:(CGFloat)currentSecond {
    [self.musicSlider setValue:currentSecond animated:YES];
}

/**
 *  通过KVO监控播放器状态
 *
 *  @param keyPath 监控属性
 *  @param object  监视器
 *  @param change  状态改变
 *  @param context 上下文
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            //            self.stateButton.enabled = YES;
            CMTime duration = [PlayerSingleton sharePlayerSingleton].playerItem.duration;// 获取视频总长度
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
            self.totalTime = [self convertTime:totalSecond];// 转换成播放时间
            self.endTime = totalSecond;
            self.endSliderLabel.text = self.totalTime;
            [self customMusicSlider:duration];// 自定义UISlider外观
            self.musicSlider.maximumValue = CMTimeGetSeconds(duration);
            NSLog(@"music total duration:%f",CMTimeGetSeconds(duration));
            [self monitoringPlayback:[PlayerSingleton sharePlayerSingleton].playerItem];// 监听播放状态
        } else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        NSLog(@"Time Interval:%f",timeInterval);
        CMTime duration = [PlayerSingleton sharePlayerSingleton].playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.musicProgress setProgress:timeInterval / totalDuration animated:YES];
    }
}

- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[[PlayerSingleton sharePlayerSingleton].player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
    
}


- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (second/3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    } else {
        [formatter setDateFormat:@"mm:ss"];
        
    }
    NSString *showtimeNew = [formatter stringFromDate:d];
//    NSLog(@"shijian:%@",showtimeNew);
    return showtimeNew;
}

- (void)customMusicSlider:(CMTime)duration {
    self.musicSlider.maximumValue = CMTimeGetSeconds(duration);
    UIGraphicsBeginImageContextWithOptions((CGSize){ 1, 1 }, NO, 0.0f);
//    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
//    [self.musicSlider setMinimumTrackImage:transparentImage forState:UIControlStateNormal];
//    [self.musicSlider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
    [self.mbProView hide:YES];
}



- (void)createMbProView
{
    // 初始化
    self.mbProView = [[[MBProgressHUD alloc] initWithView:self.view] autorelease];
    
    [self.view bringSubviewToFront:self.mbProView];
    
    [self.mbProView show:YES];
    self.mbProView.labelFont = [UIFont systemFontOfSize:13];
    // 样式 圆形进度条
    //    _mbProView.mode = MBProgressHUDModeCustomView;
    self.mbProView.mode = MBProgressHUDModeIndeterminate;
    
    self.mbProView.labelText = @"努力加载中~";
    [self.view addSubview:_mbProView];
    
    
}


// 判断是否更换歌曲
- (void) isCurrentMusic:(NSInteger)indexPath
{
    if (self.modelArr != nil) {
        [self createMbProView];
    }
    NSString *music_str = [self.modelArr[indexPath] songe_url];
    NSURL *music_url = [NSURL URLWithString:music_str];
    if (![[PlayerSingleton sharePlayerSingleton].currentMusicURL isEqualToString:music_str])
    {
        [[PlayerSingleton sharePlayerSingleton].player pause];
        [[PlayerSingleton sharePlayerSingleton] player:music_url];
        [[PlayerSingleton sharePlayerSingleton].player play];
        [PlayerSingleton sharePlayerSingleton].playState = @"YES";
        [PlayerSingleton sharePlayerSingleton].currentMusicURL = music_str;
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-pause"] forState:UIControlStateNormal];
            
        NSString *pic = [self.modelArr[indexPath] pic_url];
        NSURL *pic_url = [NSURL URLWithString:pic];
        [self.backgroundImageView sd_setImageWithURL:pic_url placeholderImage:[UIImage imageNamed:@"placeHolder.png"]];
        self.titleLabel.text = [self.modelArr[indexPath] song_name];
        [PlayerSingleton sharePlayerSingleton].index = indexPath;
        [PlayerSingleton sharePlayerSingleton].currentMusicListArr = self.modelArr;
        if (self.modelArr != nil) {
            
            [[PlayerSingleton sharePlayerSingleton].tryListenArr addObject:self.modelArr[indexPath]];
        }
        [self addNotification];
        [self addObserverToPlayerItem:[PlayerSingleton sharePlayerSingleton].playerItem];
        [self getMusicListToSingletonArr];      // 给播放列表的单例赋值
        [self addTryListenData:indexPath];
       
        }
    else
    {
        CMTime duration = [PlayerSingleton sharePlayerSingleton].playerItem.duration;// 获取视频总长度
        CGFloat totalSecond = [PlayerSingleton sharePlayerSingleton].playerItem.duration.value / [PlayerSingleton sharePlayerSingleton].playerItem.duration.timescale;// 转换成秒
        self.totalTime = [self convertTime:totalSecond];// 转换成播放时间
        self.endTime = totalSecond;
        self.endSliderLabel.text = self.totalTime;
        [self customMusicSlider:duration];// 自定义UISlider外观
        self.musicSlider.maximumValue = CMTimeGetSeconds(duration);
//        NSLog(@"music total duration:%f",CMTimeGetSeconds(duration));
        [self monitoringPlayback:[PlayerSingleton sharePlayerSingleton].playerItem];// 监听播放状态
        [self addNotification];
        [self addObserverToPlayerItem:[PlayerSingleton sharePlayerSingleton].playerItem];
    }
    
}

// 播放按钮
- (void)playClick
{
    if ([[PlayerSingleton sharePlayerSingleton].playState isEqualToString:@"NO"]) {
        [[PlayerSingleton sharePlayerSingleton].player play];
        [PlayerSingleton sharePlayerSingleton].playState = @"YES";
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-pause"] forState:UIControlStateNormal];
         [self setLockInfo];
    }
    else if([[PlayerSingleton sharePlayerSingleton].playState isEqualToString:@"YES"])
    {
        [[PlayerSingleton sharePlayerSingleton].player pause];
        [PlayerSingleton sharePlayerSingleton].playState = @"NO";
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"iconfont-play"] forState:UIControlStateNormal];
    }
    
}

// 上一首按钮
- (void)lastMusicClick
{
    if (self.indexPath > 0) {
        [self isCurrentMusic:--self.indexPath];
         [self setLockInfo];
    }
    else
    {
        UIAlertView *firstMusic = [[UIAlertView alloc] initWithTitle:nil message:@"第一首歌" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [firstMusic show];
        [firstMusic release];
        [[PlayerSingleton sharePlayerSingleton].player play];
         [self setLockInfo];
    }
}

// 下一首按钮
- (void)nextMusicClick
{
    if (self.indexPath < self.modelArr.count - 1) {
        
        [self isCurrentMusic:++self.indexPath];
//         [self setLockInfo];
    }
    else
    {
        UIAlertView *firstMusic = [[UIAlertView alloc] initWithTitle:nil message:@"已经是最后一首歌" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [firstMusic show];
        [firstMusic release];
        [[PlayerSingleton sharePlayerSingleton].player play];
//         [self setLockInfo];

    }
}

- (void)backClick
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)showMusicList
{
    
    self.musicListQueue= [[UIView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT- 20)];
    self.musicListQueue.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.musicListQueue];
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    titleView.layer.borderWidth = 0.5;
    titleView.layer.borderColor = [UIColor whiteColor].CGColor;
    [self.musicListQueue addSubview:titleView];
    
    self.bacgroundView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 20)];
    NSString *pic = [self.modelArr[[PlayerSingleton sharePlayerSingleton].index] pic_url];
    NSURL *pic_url = [NSURL URLWithString:pic];
    [self.bacgroundView sd_setImageWithURL:pic_url];
    self.bacgroundView.alpha = 0.1;
    [self.musicListQueue addSubview:self.bacgroundView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleView.frame.size.width / 3, 0, 200, 50)];
    titleLabel.text = [NSString stringWithFormat:@"播放列表(%ld首)", self.modelArr.count];
    [titleView addSubview:titleLabel];
    
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    closeButton.frame = CGRectMake(WIDTH - 50, 0, 50, 50);
    [closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    [titleView addSubview:closeButton];
    [closeButton addTarget:self action:@selector(closePage) forControlEvents:UIControlEventTouchUpInside];
    [self createTableView];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, WIDTH, HEIGHT-70 ) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.musicListQueue addSubview:self.tableView];
    self.tableView.separatorColor = [UIColor whiteColor];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    BaseModel *music = self.modelArr[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = music.song_name;
    cell.detailTextLabel.text = music.singer_name;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *pic = [self.modelArr[indexPath.row] pic_url];
    NSURL *pic_url = [NSURL URLWithString:pic];
    [self.bacgroundView sd_setImageWithURL:pic_url];
    [self isCurrentMusic:indexPath.row];
}

- (void)addTryListenData:(NSInteger)index
{
    BOOL isHave = NO;

        if (isHave == NO) {
            NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
            NSString *sandBoxPath = [sandBox lastObject];
            NSString *tryListenListPath = [sandBoxPath stringByAppendingPathComponent:@"tryListen.plist"];
            NSMutableArray *musicArr = [NSMutableArray array];
            musicArr = [NSKeyedUnarchiver unarchiveObjectWithFile:tryListenListPath];
            if (musicArr == nil) {
                musicArr = [NSMutableArray array];
            }
            BaseModel *music = self.modelArr[index];
            if (music != nil) {
                
                [musicArr addObject:music];
            }
            [NSKeyedArchiver archiveRootObject:musicArr toFile:tryListenListPath];
            NSLog(@"%@", tryListenListPath);

    }
}




- (void)closePage
{
    [self.musicListQueue removeFromSuperview];
}


-(void)setLockInfo{
    // 设置锁屏的信息
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    
    // 图片 歌曲名 歌手
    
    
    NSInteger index = [PlayerSingleton sharePlayerSingleton].index;
    BaseModel *music = [PlayerSingleton sharePlayerSingleton].currentMusicListArr[index];
    
    if (music != nil) {
        
        // 标题
        info[MPMediaItemPropertyTitle] = music.song_name;//歌曲名
        
        // 艺人
        info[MPMediaItemPropertyArtist] = music.singer_name;
        UIImage *image = [[UIImage alloc] init];
//        if (music.pic_url != nil && ![music.pic_url isEqualToString:@"http://3p.pic.ttdtweb.com/3p.ttpod.com/video/mv_pic/mv_pic_2/160_90/860/31355/219487.jpg"]) {
//            NSString *image_str = music.pic_url;
//            NSURL *image_url = [NSURL URLWithString:image_str];
//            NSData *image_data = [NSData dataWithContentsOfURL:image_url];
//            image = [UIImage imageWithData:image_data];
//        } else {
//            image = [UIImage imageNamed:@"placeHolder"];
//            
//        }
        
        
        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
        info[MPMediaItemPropertyArtwork] = artwork;
    }
    
    
    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;
    
}




- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    if (event.type == UIEventTypeRemoteControl) {
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlPlay:
                [[PlayerSingleton sharePlayerSingleton].player play];
                break;
                
            case UIEventSubtypeRemoteControlPause:
                [[PlayerSingleton sharePlayerSingleton].player pause];
                break;
                
            case UIEventSubtypeRemoteControlPreviousTrack:
                [self isCurrentMusic:--self.indexPath];
                [self setLockInfo];
                break;
                
            case UIEventSubtypeRemoteControlNextTrack:
                [self isCurrentMusic:++self.indexPath];
                [self setLockInfo];
                break;
                
            default:
                break;
        }
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
